<template>
    <div class="CompanySelector">
        <el-select
                :value="valueUse"
                @input="change"
                filterable
                :placeholder="placeholder"
                :filter-method="filterMethod"
        >
            <el-option :label="filterAllText" :value="0" v-if="isFilter"></el-option>
            <el-option v-for="item in companiesFilter"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"
            ></el-option>
        </el-select>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Watch, Vue } from 'vue-property-decorator'
import Api from "@/assets/api/Api"

@Component({
  components: {}
})
export default class CompanySelector extends Vue {
  @Prop({
    default: 0
  })
  readonly value!: any
  @Prop({
    default: false
  })
  readonly isFilter!: any
  @Prop({
    default: 0
  })
  readonly category!: any
  @Prop({
    default: '请选择'
  })
  readonly placeholder!: any
  @Prop({
    default: '全部'
  })
  readonly filterAllText!: any
  companies: Array<any> = []
  filterString: string = ''
  pinyinMatch: any = require('pinyin-match')

  mounted() {
    this.reload()
  }

  reload() {
    this.refreshList()
    this.change(0)
  }

  change(v) {
    this.$emit('input', v)
  }

  refreshList() {
    this.$ajax.request(Api.company.selectByCategory, {
      category: this.category
    }).then(resp => {
      this.companies = resp
    })
  }

  filterMethod(a) {
    this.filterString = a
  }

  @Watch('type')
  onTypeChanged() {
    this.refreshList()
  }

  get valueUse() {
    if (this.value) {
      return this.value
    }

    return this.isFilter ? 0 : null
  }

  get companiesFilter() {
    if (this.filterString === '') {
      return this.companies
    }

    return this.companies.filter(x => {
      return this.pinyinMatch.match(x.name, this.filterString)
    })
  }

}
</script>

<style lang="less" scoped>
    @import (reference) "~style/all.less";

    .CompanySelector {
    }
</style>